import { getOrderListAdmin, editOrderTrackingAdmin, confirmReturnAdmin, revokeReturnAdmin, deleteOrderAdmin, saveOrderDeliverExpressInfoAdmin, getOrderExpressInfoAdmin, getOrderExpressInfo, recoverOrderAdmin } from "../../../../api/api"
import React, { useState, useContext, useEffect, useRef } from "react";
import Link from "next/link";
import CartContext from "../../../../helpers/cart";
import { Container, Row, Col, Media, Input, Button, Modal, ModalHeader, ModalBody, Form, Label, Dropdown, DropdownToggle, DropdownMenu, DropdownItem, ButtonGroup, UncontrolledDropdown } from "reactstrap";
import { CurrencyContext } from "../../../../helpers/Currency/CurrencyContext";
import cart from "../../../../public/assets/images/icon-empty-cart.png";
// import { getCartInfo } from "../.."
import { fileServerUrl } from "../../../../config/index.json";
import { getTwoDecimal } from "../../../../tools/tools";
import { changeProductCount, removeCartProduct } from "../../../../api/api";
import { debounce } from "lodash";
import { toast } from "react-toastify";
import { useRouter } from 'next/router';

const AdminOrderListPage = () => {
  const context = useContext(CartContext);
  const cartItems = context.state;
  const curContext = useContext(CurrencyContext);
  const symbol = curContext.state.symbol;
  const maxImgSize = 1024 * 1024 * 5;
  // const total = context.cartTotal;
  // const removeFromCart = context.removeFromCart;
  const [quantity, setQty] = useState(1);
  const [quantityError, setQuantityError] = useState(false);
  const updateQty = context.updateQty;
  const [isOpen, setIsOpen] = useState(false);
  const [imgModalIsOpen, setImgModalIsOpen] = useState(false);
  const [returnModalIsOpen, setReturnModalIsOpen] = useState(false);
  const [needReturn, setNeedReturn] = useState(false);
  const [dropdownOpen1, setDropdownOpen1] = useState(false);
  const [dropdownOpen2, setDropdownOpen2] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [pageCount, setPageCount] = useState(1);
  const [list, setList] = useState([]);
  const [deliverList, setDeliverList] = useState([]);
  const [returnList, setReturnList] = useState([]);

  const [formData, setFormData] = useState({
    "order_id": "",
    "product_name": "",
    "quantity": "",
    "total_price": "",
    "order_status": "",
    "create_date": "",
    "tracking_number": "",
    "tracking_img": "",
    "deliver_date": "",
    "return_tracking_number": "",
    "return_tracking_img": "",
    "return_reason": "",
    "order_status_code": "",
    "return_date": "",
    "return_number_tip": "",
    "return_reason_tip": "",
    "user_name": ""
  });
  const [total, setTotal] = useState(0);
  const [qtyList, setQtyList] = useState([]);
  const [lineTotal, setLineTotal] = useState(0);
  const [filter, setFilter] = useState(-1);
  const [imgBase64, setImgBase64] = useState("");
  const [trackingNumber, setTrackingNumber] = useState("");
  const [returnReasonTip, setReturnReasonTip] = useState("");
  const [returnNumberTip, setReturnNumberTip] = useState("");
  const [keyword, setKeyword] = useState("");

  const [loading, setLoading] = useState(false);

  const [deleteId, setDeleteId] = useState("");
  const [recoverId, setRecoverId] = useState("");
  const [confirmModel, setConfirmModel] = useState(false);
  const [recoverModel, setRecoverModel] = useState(false);

  const [expressList, setExpressList] = useState([{
    "tracking_number": "",
    "express_company": ""
  }]);
  const [selectedId, setSelectedId] = useState("");
  const [expressModel, setExpressModel] = useState(false);

  const debounceRef = useRef(null);
  const router = useRouter();

  const [expressModelType, setExpressModelType] = useState(0);
  useEffect(() => {
    var userInfo = localStorage.getItem("XYCLogin");
    if (userInfo) {
      if (JSON.parse(userInfo).user_guid) {
        getOrderListAdmin({ keyword: "", "filter": "-1", "pageNum": "1", "pageSize": "10" }).then(res => {
          setList(res.data);
          setPageCount(res.page_count)
        });
      }
    }
  }, [window.onload])

  useEffect(() => {

    var user = localStorage.getItem("XYCLogin")
    if (!user) {
      toast.error("Please Login To Shopping!");
      router.push("/");
    }

    debounceRef.current = debounce((item, quantity) => {
      changeProductCount({
        product_id: item.product_id,
        quantity: quantity
      })
    }, 1000);

    return () => {
      if (debounceRef.current) {
        debounceRef.current.cancel();
      }
    };
  }, [])

  const onKeywordChange = (e) => {
    setKeyword(e.target.value);
  }

  const ViewDetail = (item) => {
    setIsOpen(true);
    setFormData({
      "order_id": item.order_id,
      "product_name": item.product_name,
      "quantity": item.order_num,
      "total_price": item.total_price,
      "order_status": item.order_status_desc,
      "create_date": item.create_date,
      "tracking_number": item.tracking_number,
      "tracking_img": item.tracking_img,
      "deliver_date": item.deliver_date,
      "return_tracking_number": item.return_tracking_number,
      "return_tracking_img": item.return_tracking_img,
      "return_reason": item.return_reason,
      "order_status_code": item.order_status_code,
      "return_date": item.return_date,
      "return_number_tip": item.return_number_tip,
      "return_reason_tip": item.return_reason_tip,
      "user_name": item.user_name
    });
    getOrderExpressInfoAdmin({
      "order_id": item.order_id
    }).then(res => {
      setDeliverList(res.express_info);
    });
    getOrderExpressInfo({
      "order_id": item.order_id
    }).then(res => {
      setReturnList(res.express_info);
    });
  }

  const AddPage = () => {
    if (pageNum < pageCount) {
      getOrderListAdmin({ "keyword": keyword, "filter": `${filter}`, "pageNum": `${pageNum + 1}`, "pageSize": "10" }).then(res => {
        setList(res.data);
        setPageCount(res.page_count)
      });
      setPageNum(pageNum + 1);
    }
  }

  const MinusPage = () => {
    if (pageNum > 1) {
      getOrderListAdmin({ "keyword": keyword, "filter": `${filter}`, "pageNum": `${pageNum - 1}`, "pageSize": "10" }).then(res => {
        setList(res.data);
        setPageCount(res.page_count)
      });
      setPageNum(pageNum - 1);
    }
  }

  const ChangeFilter = (filterNum) => {
    setFilter(filterNum);
    getOrderListAdmin({ "keyword": keyword, "filter": `${filterNum}`, "pageNum": `${pageNum}`, "pageSize": "10" }).then(res => {
      setList(res.data);
      setPageCount(res.page_count)
    });
  }


  const isImageFile = (filename) => {
    const extensions = ['.jpg', '.jpeg', '.png'];
    return extensions.some(extension => filename.toLowerCase().endsWith(extension));
  }

  const handleReUploadBtnOnclick = () => {
    document.getElementById("reUploadRealBtn").click();

  }


  const UpdateTrackingNumber = (index, e, type) => {
    var list = expressList;
    if (type == '0') {
      list[index].tracking_number = e.target.value;
    }
    else {
      list[index].express_company = e.target.value;
    }
    setExpressList(list);
  }

  const UpdateReturnReasonTip = (e) => {
    setReturnReasonTip(e.target.value);
  }

  const UpdateReturnNumberTip = (e) => {
    setReturnNumberTip(e.target.value);
  }

  const UpdateOrderInfo = (order_id) => {
    setLoading(true);
    editOrderTrackingAdmin({
      "tracking_number": trackingNumber,
      "tracking_image": imgBase64,
      "order_id": order_id,
      "return_reason_tip": returnReasonTip,
      "return_number_tip": returnNumberTip
    }).then(res => {
      setLoading(false);
      if (res.error_code == "2000") {
        location.reload();
        toast.success("Update Order Succeed.")
      }
      else {
        toast.error(res.msg)
      }
    })
  }

  const RevokeReturnAdmin = (order_id) => {
    revokeReturnAdmin({
      "order_id": order_id
    }).then(res => {
      if (res.error_code == "2000") {
        location.reload();
        toast.success("Revoke Return Succeed.")
      }
      else {
        toast.error(res.msg)
      }
    })
  }

  const ConfirmReturnAdmin = (order_id) => {
    confirmReturnAdmin({
      "order_id": order_id
    }).then(res => {
      if (res.error_code == "2000") {
        location.reload();
        toast.success("Confirm Return Succeed.")
      }
      else {
        toast.error(res.msg)
      }
    })
  }

  const DeleteOrder = (id) => {
    deleteOrderAdmin({
      id: id
    }).then(res => {
      if (res.error_code == "2000") {
        toast.success("Delete Succeed.");
        location.reload();
      }
      else {
        toast.error(res.msg);
      }
    })
  }

  const RecoverOrder = () => {
    recoverOrderAdmin({ id: recoverId }).then(res => {
      if (res.error_code == "2000") {
        toast.success("Recover Succeed.");
        location.reload();
      }
      else {
        toast.error(res.msg);
      }
    })
  }

  const AddDeliverNumber = (orderId) => {
    setExpressModel(true);
    setSelectedId(orderId);
    setExpressModelType(1);
    getOrderExpressInfoAdmin({
      "order_id": orderId
    }).then(res => {
      if (res.express_info.length > 0) {
        setExpressList(res.express_info);
      }
    });
  }

  const SaveDeliverInfo = () => {
    setLoading(true);
    var filteredInfo = expressList.filter(item =>
      item.tracking_number != "" || item.express_company != ""
    );
    setExpressList(filteredInfo);
    if (filteredInfo.length > 0) {
      saveOrderDeliverExpressInfoAdmin({
        "order_id": selectedId,
        "express_info": filteredInfo
      }).then(res => {
        if (res.error_code == "2000") {
          toast.success("Express Info Saved.");
          setDeliverList(filteredInfo);
        }
        else {
          toast.warning("Save Express Info Failed.")
        }
        setLoading(false);
        setExpressModel(false);
        setExpressList([{
          "tracking_number": "",
          "express_company": ""
        }]);
      });
    }
    else {
      toast.warning("At Least One Piece Of Express Info Is Required.")
      setExpressModel(false);
      setLoading(false);
      setExpressList([{
        "tracking_number": "",
        "express_company": ""
      }]);
    }
  }

  const ViewReturnNumber = (orderId) => {
    setExpressModelType(0);
    setExpressModel(true);
    getOrderExpressInfo({
      "order_id": orderId
    }).then(res => {
      if (res.express_info.length > 0) {
        setExpressList(res.express_info);
      }
    });
  }

  const ReturnColor = (status_code) => {
    switch (status_code) {
      case '0':
        return 'red';
      case '1':
        return '#f39c12';
      case '2':
        return '#2ecc71';
      case '4':
        return '#2980b9';
      // #0A0A85
      case '5':
        return '#2E4E7E';
      default:
        return 'grey';
    }
  }

  const onSearchClick = () => {
    getOrderListAdmin({ "keyword": keyword, "filter": `${filter}`, "pageNum": "1", "pageSize": "10" }).then(res => {
      setList(res.data);
      setPageCount(res.page_count)
    });
  }

  return (
    <div>
      <Modal isOpen={expressModel} centered size="lg" style={{ width: 600 }}>
        <ModalHeader >EXPRESS</ModalHeader>
        <ModalBody>
          <div className="checkout-form">
            {
              expressList.map((item, index) => {
                return (
                  <>
                    <Row>
                      <Col md="6">
                        <Label for="trackingNumber">Tracking Number</Label>
                        {/* 为空则显示未发货 */}
                        <Input type="text" disabled={expressModelType == '0'} className="form-control" id="trackingNumber" name="trackingNumber" onChange={(e) => { UpdateTrackingNumber(index, e, 0) }} placeholder="Please Enter" defaultValue={item.tracking_number} />
                      </Col>
                      <Col md="6">
                        <Label for="trackingNumber">Express Company</Label>
                        {/* 为空则显示未发货 */}
                        <Input type="text" disabled={expressModelType == '0'} className="form-control" id="expressCompany" name="expressCompany" onChange={(e) => { UpdateTrackingNumber(index, e, 1) }} placeholder="Please Enter" defaultValue={item.express_company} />
                      </Col>
                    </Row>
                  </>
                )
              })
            }
            <Row>
              <Col md="4">
                {
                  expressModelType == '1' &&
                  <Button style={{ width: "100%", marginTop: 20 }} color="primary" disabled={loading} onClick={SaveDeliverInfo}>Save</Button>
                }
              </Col>
              <Col md="4">
                {
                  expressModelType == '1' &&
                  <Button style={{ width: "100%", marginTop: 20 }} disabled={loading} color="primary" onClick={() => {
                    if (expressList.length < 5) {
                      setExpressList([...expressList, {
                        "tracking_number": "",
                        "express_company": ""
                      }]);
                    }
                  }}>Add</Button>
                }

              </Col>
              <Col md="4">
                <Button style={{ width: "100%", marginTop: 20 }} onClick={() => {
                  setExpressModel(false);
                  setExpressList([{
                    "tracking_number": "",
                    "express_company": ""
                  }]);
                }}>Cancel</Button>
              </Col>
            </Row>
          </div>

        </ModalBody>
      </Modal>

      <Modal isOpen={confirmModel} centered size="lg" style={{ width: 350 }}>
        <ModalHeader >Confirm</ModalHeader>
        <ModalBody>
          <Row>
            <div style={{ marginLeft: 40, marginTop: 20 }}>
              <h3>Confirm to delete order?</h3>
            </div>
          </Row>
          <Row>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} onClick={() => { setConfirmModel(false) }}>Cancel</Button>
              </div>
            </Col>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} color="primary" onClick={() => { DeleteOrder(deleteId) }}>Confirm</Button>
              </div>
            </Col>
          </Row>
        </ModalBody>
      </Modal>

      <Modal isOpen={recoverModel} centered size="lg" style={{ width: 350 }}>
        <ModalHeader >Confirm</ModalHeader>
        <ModalBody>
          <Row>
            <div style={{ marginLeft: 40, marginTop: 20 }}>
              <h3>Confirm to recover order?</h3>
            </div>
          </Row>
          <Row>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} onClick={() => { setRecoverModel(false) }}>Cancel</Button>
              </div>
            </Col>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} color="primary" onClick={() => { RecoverOrder() }}>Confirm</Button>
              </div>
            </Col>
          </Row>
        </ModalBody>
      </Modal>

      {/* imgModalIsOpen */}
      <Modal isOpen={imgModalIsOpen} centered size="lg">
        <ModalHeader >Image Viewer</ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <img src={formData.tracking_img ? `${fileServerUrl}/${formData.tracking_img}` : `${fileServerUrl}/products/default.jpg`} width={"100%"} height={"100%"} />
              </Col>
            </Row>
            <div style={{ marginTop: 20 }}>
              <Row>
                <Col sm="6"><Button style={{ width: "100%" }} disabled={loading} onClick={handleReUploadBtnOnclick} color="primary">Upload</Button></Col>
                <Col sm="6"><Button style={{ width: "100%" }} disabled={loading} onClick={() => { setImgModalIsOpen(false) }}>Cancel</Button></Col>
              </Row>
            </div>
          </div>
        </ModalBody>
      </Modal>

      <Modal isOpen={returnModalIsOpen} centered size="lg">
        <ModalHeader >Image Viewer</ModalHeader>
        <ModalBody>
          <div className="user-form">
            <Row>
              <Col sm="12">
                <img src={formData.return_tracking_img ? `${fileServerUrl}/${formData.return_tracking_img}` : `${fileServerUrl}/products/default.jpg`} width={"100%"} height={"100%"} />
              </Col>
            </Row>
            <div style={{ marginTop: 20 }}>
              <Row>
                <Col sm="12"><Button style={{ width: "100%" }} disabled={loading} onClick={() => { setReturnModalIsOpen(false) }}>Cancel</Button></Col>
              </Row>
            </div>
          </div>
        </ModalBody>
      </Modal>

      <Modal isOpen={isOpen} centered size="lg">
        <ModalHeader >Order Info</ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <Form className="theme-form">
                  <Row>
                    <Col sm="12">

                    </Col>
                  </Row>
                  <Row>
                    <Col md="4">
                      <Label for="orderId">Order Id</Label>
                      <h4>{formData.order_id}</h4>
                    </Col>
                    <Col md="3">
                      <Label for="productName">Product Name</Label>
                      <h4>{formData.product_name}</h4>
                    </Col>
                    <Col md="2">
                      <Label for="quantity">Quantity</Label>
                      <h4>{formData.quantity}</h4>
                    </Col>
                    <Col md="2">
                      <Label for="totalPrice">Total Price</Label>
                      <h4>{symbol} {formData.total_price}</h4>
                    </Col>
                  </Row>
                  <Row>
                    <Col md="4">
                      <Label for="orderStatus">Order Status</Label>
                      <h4>{formData.order_status}</h4>
                    </Col>
                    <Col md="3">
                      <Label for="orderStatus">Buyer Name</Label>
                      <h4>{formData.user_name}</h4>
                    </Col>
                    <Col md="4">
                      <Label for="createDate">Create Date</Label>
                      <h4>{formData.create_date}</h4>
                    </Col>
                  </Row>
                  <Row style={{ justifyContent: 'center', marginTop: 30 }}>
                    <div>
                      <span style={{ fontWeight: 800, fontSize: 26, alignItems: 'center' }}>DELIVER INFO</span>
                    </div>
                  </Row>
                  {
                    deliverList.length > 0 &&
                    <Row style={{ justifyContent: 'center ' }}>
                      {/* <Col sm="12"> */}
                      <table style={{ width: '100%', marginLeft: 15 }}>
                        <thead>
                          <tr className="table-head">
                            <th scope="col">ID</th>
                            <th scope="col">Express Company</th>
                            <th scope="col">Tracking Number</th>
                          </tr>
                        </thead>
                        {deliverList.map((item, index) => {
                          return (
                            <tbody key={index}>
                              <tr>
                                <td>
                                  <h5>{index + 1}</h5>
                                </td>
                                <td>
                                  <h4>
                                    {item.express_company}
                                  </h4>
                                </td>
                                <td>
                                  <h4>
                                    {item.tracking_number}
                                  </h4>
                                </td>
                              </tr>
                            </tbody>
                          );
                        })}
                      </table>
                      {/* </Col> */}
                    </Row>
                  }

                  <Row>
                    <Col md="4">
                      <Label for="trackingNumber">Tracking Info</Label>
                      {/* 为空则显示未发货 */}
                      <div>
                        <Button disabled={formData.order_status_code != '1' && formData.order_status_code != '2'} color="primary" onClick={() => AddDeliverNumber(formData.order_id)}>{deliverList.length > 0 ? 'EDIT' : 'ADD'}</Button>
                      </div>
                      {/* <Input type="text" className="form-control" id="trackingNumber" name="trackingNumber" onChange={UpdateTrackingNumber} placeholder="Please Enter" disabled={formData.order_status_code != '1' && formData.order_status_code != '2'} defaultValue={formData.tracking_number} /> */}
                    </Col>
                    {/* <Col md="4">
                      <Label for="trackingImage">Tracking Image</Label>
                      {
                        formData.tracking_img ? <div><input type="file" id="reUploadRealBtn" name="uploadRealBtn" accept="image/jpeg, image/png" style={{ display: 'none' }} onChange={handleFileReChange} /><Button color="primary" disabled={formData.order_status_code != '1' && formData.order_status_code != '2'} onClick={() => { setImgModalIsOpen(true) }}>Edit</Button></div> : <div><input type="file" id="uploadRealBtn" name="uploadRealBtn" accept="image/jpeg, image/png" style={{ display: 'none' }} onChange={handleFileChange} /><Button color="primary" disabled={formData.order_status_code != '1' && formData.order_status_code != '2'} onClick={handleUploadBtnOnclick}>Upload</Button></div>
                      }
                    </Col> */}
                    <Col md="4">
                      <Label for="deliverDate">Deliver Date</Label>
                      {/* 为空则显示未发货 */}
                      <div>{formData.deliver_date}</div>
                      {/* <a>1111111111111111.jpg</a> */}
                    </Col>
                  </Row>
                  <Row style={{ justifyContent: 'center', marginTop: 30 }}>
                    <div>
                      <span style={{ fontWeight: 800, fontSize: 26, alignItems: 'center' }}>RETURN INFO</span>
                    </div>
                  </Row>
                  {
                    returnList.length > 0 &&
                    <Row style={{ justifyContent: 'center ' }}>
                      {/* <Col sm="12"> */}
                      <table style={{ width: '100%', marginLeft: 15 }}>
                        <thead>
                          <tr className="table-head">
                            <th scope="col">ID</th>
                            <th scope="col">Express Company</th>
                            <th scope="col">Tracking Number</th>
                          </tr>
                        </thead>
                        {returnList.map((item, index) => {
                          return (
                            <tbody key={index}>
                              <tr>
                                <td>
                                  <h5>{index + 1}</h5>
                                </td>
                                <td>
                                  <h4>
                                    {item.express_company}
                                  </h4>
                                </td>
                                <td>
                                  <h4>
                                    {item.tracking_number}
                                  </h4>
                                </td>
                              </tr>
                            </tbody>
                          );
                        })}
                      </table>
                      {/* </Col> */}
                    </Row>
                  }
                  <>
                    <Row>
                      {/* <Col md="4">
                        <Label for="returnTrackingNumber">Return Tracking Info</Label>
                        <div>
                          <Button disabled={formData.order_status_code != '2' && formData.order_status_code != '4'} color="primary" onClick={() => ViewReturnNumber(formData.order_id)}>View</Button>
                        </div>
                      </Col> */}
                      <Col md="4">
                        <Label for="returnTrackingNumber" style={{ color: 'green' }}>Return Tracking Number Tip</Label>
                        <Input type="text" className="form-control" id="returnNumberTip" name="returnNumberTip" placeholder="Visible To Admin" onChange={UpdateReturnNumberTip} defaultValue={formData.return_number_tip} />
                      </Col>
                      {/* <Col md="4">
                        <Label for="returnTrackingImage">Return Tracking Image</Label>
                        <div>
                          {
                            formData.return_tracking_img ?
                              <Button disabled={formData.return_tracking_img == "" || loading} color="success" onClick={() => { setReturnModalIsOpen(true) }}>View</Button>
                              : <a>{formData.return_tracking_img}</a>
                          }
                        </div>
                      </Col> */}
                      <Col md="4">
                        <Label for="deliverDate">Return Date</Label>
                        {/* 为空则显示未发货 */}
                        <div>{formData.return_date}</div>
                        {/* <a>1111111111111111.jpg</a> */}
                      </Col>
                      <Col md="12">
                        <Label for="returnReason">Return Reason</Label>
                        <Input type="textarea" style={{ height: 100 }} className="form-control" id="returnReason" name="returnReason" placeholder="Product Description, Max length: 400 digits." maxLength={400}
                          required="" disabled contentEditable={false} value={formData.return_reason} />
                      </Col>
                      <Col md="12">
                        <Label for="returnReason" style={{ color: 'green' }}>Return Reason Tip</Label>
                        <Input type="textarea" style={{ height: 40 }} className="form-control" id="returnReasonTip" name="returnReasonTip" placeholder="Visible To Admin" maxLength={400}
                          required="" contentEditable={false} value={formData.return_reason_tip} onChange={UpdateReturnReasonTip} />
                      </Col>
                    </Row>
                  </>

                  <div className="admin-user-form-btn-list">
                    <Row>
                      <Col md="3">
                      </Col>
                      <Col md="3">
                        {
                          formData.order_status_code == '4' && <Button color="primary" href={null} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={formData.order_status_code != '4' || loading} onClick={() => { RevokeReturnAdmin(formData.order_id) }}>Revoke</Button>
                        }
                      </Col>
                      <Col md="3">
                        {
                          formData.order_status_code != '4' ?
                            <Button href={null} color="primary" style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} onClick={() => { UpdateOrderInfo(formData.order_id) }} disabled={(formData.order_status_code != '1' && formData.order_status_code != '2') || loading} >Save</Button>
                            :
                            <Button href={null} color="primary" style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={formData.order_status_code != '4' || loading} onClick={() => { ConfirmReturnAdmin(formData.order_id) }}>Confirm</Button>
                        }
                      </Col>
                      <Col md="3">
                        <Button href={null} onClick={() => { setIsOpen(false); setNeedReturn(false) }} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={loading} >Cancel</Button>
                      </Col>
                    </Row>
                  </div>
                </Form>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>
      <div>
        <div className="order-list-filter-btn-list">
          <Row>
            <Col md="1">
            </Col>
            <Col md="2">
              <ButtonGroup>
                <UncontrolledDropdown>
                  <DropdownToggle caret>
                    Filter
                  </DropdownToggle>
                  <DropdownMenu>
                    <DropdownItem active={filter == '-1'} onClick={() => { ChangeFilter(-1) }}>
                      All
                    </DropdownItem>
                    <DropdownItem active={filter == '0'} onClick={() => { ChangeFilter(0) }}>
                      Unpaid
                    </DropdownItem>
                    <DropdownItem active={filter == '1'} onClick={() => { ChangeFilter(1) }}>
                      Undelivered
                    </DropdownItem>
                    <DropdownItem active={filter == '2'} onClick={() => { ChangeFilter(2) }}>
                      Delivered
                    </DropdownItem>
                    <DropdownItem active={filter == '3'} onClick={() => { ChangeFilter(3) }}>
                      Completed
                    </DropdownItem>
                    <DropdownItem active={filter == '4'} onClick={() => { ChangeFilter(4) }}>
                      Processing
                    </DropdownItem>
                    <DropdownItem active={filter == '5'} onClick={() => { ChangeFilter(5) }}>
                      Returned
                    </DropdownItem>
                    <DropdownItem active={filter == '-2'} onClick={() => { ChangeFilter(-2) }}>
                      Deleted
                    </DropdownItem>
                  </DropdownMenu>
                </UncontrolledDropdown>
              </ButtonGroup>
            </Col>
            <Col md="4">
            </Col>
            <Col md="3"><Input type="text" className="form-control" id="keyword" name="keyword" onChange={onKeywordChange} placeholder="Please enter Product Name, Email or Order Id." /></Col>
            <Col md="1"><a href={null} style={{ width: 120, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={onSearchClick} >Search</a></Col>
            <Col md="1">
            </Col>
          </Row>
        </div>
        {list && list.length > 0 ? (
          <section className="cart-section section-b-space">
            <Container>
              <Row>
                <Col sm="12">
                  <table className="table cart-table table-responsive-xs">
                    <thead>
                      <tr className="table-head">
                        <th scope="col">product</th>
                        <th scope="col">product name</th>
                        <th scope="col">order id</th>
                        <th scope="col">payment id</th>
                        <th scope="col">total price</th>
                        <th scope="col">order status</th>
                        <th scope="col">create date</th>
                        <th scope="col">action</th>
                      </tr>
                    </thead>
                    {list.map((item, index) => {
                      return (
                        <tbody key={index}>
                          <tr>
                            <td>
                              <Link href={`/product-details/` + item.product_id}>
                                <a className="order-list-product">
                                  <Media
                                    src={item.product_img ? `${fileServerUrl}/${item.product_img}` : `${fileServerUrl}/products/default.jpg`}
                                    alt=""
                                  />
                                </a>
                              </Link>
                            </td>
                            <td>
                              <Link href={`/product-details/` + item.product_id}>
                                <a>{item.product_name}</a>
                              </Link>
                            </td>
                            <td>
                              <h4>
                                {item.order_id}
                              </h4>
                            </td>
                            <td>
                              <h4>
                                {item.payment_id}
                              </h4>
                            </td>
                            <td>
                              <h2 className="td-color">
                                {symbol}
                                {getTwoDecimal(item.total_price)}
                              </h2>
                            </td>
                            <td>
                              {/* <span style={{ color: ReturnColor(item.order_status_code) }}> */}
                              <div style={{ backgroundColor: ReturnColor(item.order_status_code), width: '50%', borderRadius: 5, marginLeft: '25%' }}>
                                <span style={{ color: "white" }}>
                                  {item.order_status_desc}
                                </span>
                              </div>
                              {/* </span> */}
                            </td>
                            <td>
                              {item.create_date}
                            </td>
                            <td>
                              <Button color="success" className="admin-product-acion" onClick={() => { ViewDetail(item) }}>View</Button>
                              {
                                item.order_status_code != '6' &&
                                <Button className="admin-product-acion" onClick={() => { setConfirmModel(true); setDeleteId(item.order_id); }}>Delete</Button>
                              }
                              {
                                item.order_status_code == '6' &&
                                <Button className="admin-product-acion" onClick={() => { setRecoverModel(true); setRecoverId(item.order_id); }}>Recover</Button>
                              }
                            </td>
                          </tr>
                        </tbody>
                      );
                    })}
                  </table>
                </Col>
              </Row>
            </Container>
            <div className="order-list-page-select-btn" style={{ marginTop: 50 }}>
              <Button className="page-select-btn1" onClick={MinusPage}>Last Page</Button><span className="page-select-label">{pageNum} IN {pageCount}</span><Button className="page-select-btn2" onClick={AddPage}>Next Page</Button>
            </div>
          </section>
        ) : (
          <section className="cart-section section-b-space">
            <Container>
              <Row>
                <Col sm="12">
                  <div>
                    <div className="col-sm-12 empty-cart-cls text-center">
                      <Media
                        src={cart}
                        className="img-fluid mb-4 mx-auto"
                        alt=""
                      />
                      <h3>
                        <strong>Your Order Is Empty</strong>
                      </h3>
                    </div>
                  </div>
                </Col>
              </Row>
            </Container>
          </section>
        )}
      </div>
    </div>
  );
};

export default AdminOrderListPage;
